package com.vito.oa.preview.action;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.vito.base.authoriza.action.BaseAction;
import com.vito.base.authoriza.cache.SessionMap;
import com.vito.base.authoriza.model.FileModel;
import com.vito.base.authoriza.model.UserModel;
import com.vito.base.authoriza.service.FileService;
import com.vito.base.exception.ParamErrorException;
import com.vito.base.model.FtpModel;
import com.vito.base.model.Result;
import com.vito.base.util.FTPUtil;
import com.vito.base.util.FtpHelper;
import com.vito.base.util.Pty;
import com.vito.oa.preview.model.PreviewFileModel;
import com.vito.oa.preview.service.PreviewFileService;
import com.vito.oa.preview.util.Doc2HtmlUtil;
import com.vito.oa.preview.util.PreviewUtil;

import sun.net.ftp.FtpClient;

@SuppressWarnings("restriction")
@Controller
@RequestMapping("oa/preview")
public class PreviewFileAction extends BaseAction{

	private static final Logger logger = LoggerFactory.getLogger(PreviewFileAction.class);
	private Pty pty = Pty.get("conf/ftp");

	private String sers = pty.getProp("server.sign"),ip=null,username=null,password=null,path=null,name=null;
	private String[] ss = sers.split(",");
	FTPUtil ftp = null;
	FtpHelper ftpHelper = null;
	@Reference
	private PreviewFileService previewFileService;
	@Reference
	private FileService fileService;

	/**
	 * office文件预览，需要进行转换成PDF
	 * @param fileId
	 * @param request
	 * @param response
	 * @return
	 * @throws ParamErrorException 
	 */

	@ResponseBody
	@RequestMapping("/file/previewOffice")
	public Result previewOffice(String fileId,HttpServletRequest request,HttpServletResponse response) throws ParamErrorException{
		/**
		 * 读取ftp配置文件信息
		 */
		FtpModel ftpModel = new FtpModel();
		if(ss!=null&&ss.length>0){
			for(int i=0;i<ss.length;i++){
				ip = pty.getProp(new StringBuilder("server.").append(ss[i]).append(".ip").toString());
				if(ip==null||"".equals(ip))
					throw new ParamErrorException(new StringBuilder("配置文件conf/ftp 缺少server.").append(ss[i]).append(".ip").toString());
				username = pty.getProp(new StringBuilder("server.").append(ss[i]).append(".username").toString());
				if(username==null||"".equals(username))
					throw new ParamErrorException(new StringBuilder("配置文件conf/ftp 缺少server.").append(ss[i]).append(".username").toString());
				password = pty.getProp(new StringBuilder("server.").append(ss[i]).append(".password").toString());
				if(password==null||"".equals(password))
					throw new ParamErrorException(new StringBuilder("配置文件conf/ftp 缺少server.").append(ss[i]).append(".password").toString());
				try{
					ftp = new FTPUtil(ip, username, password);

					break;
				}catch(Exception e){
					logger.warn(new StringBuilder("IP:").append(ip).append(" FTP服务器缺少资源文件：").append(ftpModel).toString());
				}
			}
		}else{
			throw new ParamErrorException("配置文件conf/ftp 缺少server.sign");
		}
		Result res = new Result();
		UserModel user = SessionMap.getObj();
		FileModel fmodel = new FileModel();
		String convertFilePath = null;
		String originalFileName = null;
		String path = null;
		PreviewFileModel convertFile = previewFileService.getPreviewPath(fileId);
		if(convertFile!=null){
			path = convertFile.getConvertFilePath();
			String fileSavePath = request.getRealPath("/").concat("resource/filePreview").concat("/").concat(path);
			File file = new File(fileSavePath);
			if(file.exists()){
				Map<String, String> map = new HashMap<String,String>();
				map.put("convertFilePath",path );
				res.setCode(Result.CODE_OK);
				res.setData(map);
				return res;
			}else{
				boolean flag = previewFileService.deletePreviewPath(fileId);
				List<FileModel> files = fileService.queryFile(fmodel);
				if(files!=null&&files.size()>0){
					for (int i = 0; i < files.size(); i++) {
						if(files.get(i).getFileId().equals(fileId)){
							originalFileName = files.get(i).getFileName()+"."+files.get(i).getFileExt();
							ftpModel.setFileNewName(files.get(i).getFileId()+"."+files.get(i).getFileExt());
							ftpModel.setOldName(files.get(i).getFileName());
							ftpModel.setFilePath(files.get(i).getFilePath().replace("_", "/"));
							try {
								//登录到ftp服务器
								FTPUtil ftpUtil = new FTPUtil(ip, username, password);
								FtpClient ftp = ftpUtil.connectFTP();
								//获取文件流
								InputStream in = ftp.getFileStream(ftpModel.getFilePath().substring(1, ftpModel.getFilePath().length())+ftpModel.getFileNewName());
								//由文件流转换成pdf
								convertFilePath = convertToPDF(request, originalFileName, in, user.getUserId());
								if(null!=convertFilePath){
									path = user.getUserId().concat("/").concat(convertFilePath);
									PreviewFileModel pfmodel = new PreviewFileModel();
									pfmodel.setConvertFilePath(path);
									pfmodel.setFileId(fileId);
									pfmodel.setFileName(originalFileName);
									if(flag){
										previewFileService.savePreviewFile(pfmodel);
									}
									Map<String, String> map = new HashMap<String,String>();
									map.put("convertFilePath",path );
									res.setCode(Result.CODE_OK);
									res.setData(map);
									return res;
								}else{
									res.setCode(Result.CODE_ERROR);
									res.setMsg("文件转换出错！");
									return res;
								}				
							} catch (Exception e) {
								logger.error(e.getMessage());
								res.setCode(Result.CODE_ERROR);
								res.setMsg("文件获取错误！");
								return res;
							}	
						}
					}
				}
			}
		}else{
			List<FileModel> files = fileService.queryFile(fmodel);
			if(files!=null&&files.size()>0){
				for (int i = 0; i < files.size(); i++) {
					if(files.get(i).getFileId().equals(fileId)){
						originalFileName = files.get(i).getFileName()+"."+files.get(i).getFileExt();
						ftpModel.setFileNewName(files.get(i).getFileId()+"."+files.get(i).getFileExt());
						ftpModel.setOldName(files.get(i).getFileName());
						ftpModel.setFilePath(files.get(i).getFilePath().replace("_", "/"));
						try {
							//登录到ftp服务器
							FTPUtil ftpUtil = new FTPUtil(ip, username, password);
							FtpClient ftp = ftpUtil.connectFTP();
							//获取文件流
							InputStream in = ftp.getFileStream(ftpModel.getFilePath().substring(1, ftpModel.getFilePath().length())+ftpModel.getFileNewName());
							//由文件流转换成pdf
							convertFilePath = convertToPDF(request, originalFileName, in, user.getUserId());
							if(null!=convertFilePath){
								path = user.getUserId().concat("/").concat(convertFilePath);
								PreviewFileModel pfmodel = new PreviewFileModel();
								pfmodel.setConvertFilePath(path);
								pfmodel.setFileId(fileId);
								pfmodel.setFileName(originalFileName);
								previewFileService.savePreviewFile(pfmodel);
								Map<String, String> map = new HashMap<String,String>();
								map.put("convertFilePath",path );
								res.setCode(Result.CODE_OK);
								res.setData(map);
								return res;
							}else{
								res.setCode(Result.CODE_ERROR);
								res.setMsg("文件转换出错！");
								return res;
							}				
						} catch (Exception e) {
							logger.error(e.getMessage());
							res.setCode(Result.CODE_ERROR);
							res.setMsg("文件获取错误！");
							return res;
						}	
					}
				}
			}
		
		}
		logger.error("预览失败！");
		res.setCode(Result.CODE_ERROR);
		res.setMsg("预览出错，请检查文件类型！");
		return res;
	}
	/**
	 * 非office类型文件预览
	 * @param fileId
	 * @param request
	 * @param response
	 * @return
	 * @throws ParamErrorException 
	 */
	@ResponseBody
	@RequestMapping("/file/previewOtherFile")
	public Result previewOtherFile(String fileId,HttpServletRequest request,HttpServletResponse response) throws ParamErrorException{
		FtpModel ftpModel = new FtpModel();
		if(ss!=null&&ss.length>0){
			for(int i=0;i<ss.length;i++){
				ip = pty.getProp(new StringBuilder("server.").append(ss[i]).append(".ip").toString());
				if(ip==null||"".equals(ip))
					throw new ParamErrorException(new StringBuilder("配置文件conf/ftp 缺少server.").append(ss[i]).append(".ip").toString());
				username = pty.getProp(new StringBuilder("server.").append(ss[i]).append(".username").toString());
				if(username==null||"".equals(username))
					throw new ParamErrorException(new StringBuilder("配置文件conf/ftp 缺少server.").append(ss[i]).append(".username").toString());
				password = pty.getProp(new StringBuilder("server.").append(ss[i]).append(".password").toString());
				if(password==null||"".equals(password))
					throw new ParamErrorException(new StringBuilder("配置文件conf/ftp 缺少server.").append(ss[i]).append(".password").toString());
				try{
					ftp = new FTPUtil(ip, username, password);

					break;
				}catch(Exception e){
					logger.warn(new StringBuilder("IP:").append(ip).append(" FTP服务器缺少资源文件：").append(ftpModel).toString());
				}
			}
		}else{
			throw new ParamErrorException("配置文件conf/ftp 缺少server.sign");
		}
		Result res = new Result();
		res.setCode(Result.CODE_OK);
		FileModel fmodel = new FileModel();
		String filePath = null;
		String originalFileName = null;
		List<FileModel> files = fileService.queryFile(fmodel);
		if(files!=null&&files.size()>0){
			for (int i = 0; i < files.size(); i++) {
				if(files.get(i).getFileId().equals(fileId)){
					filePath = files.get(i).getFilePath();
					originalFileName = files.get(i).getFileName()+"."+files.get(i).getFileExt();
					ftpModel.setFileNewName(files.get(i).getFileId()+"."+files.get(i).getFileExt());
					ftpModel.setOldName(files.get(i).getFileName());
					ftpModel.setFilePath(filePath.replace("_", "/"));

					if(PreviewUtil.isFileCanShow(originalFileName.toLowerCase())){
						try {
							FTPUtil ftpUtil = new FTPUtil(ip, username, password);
							FtpClient ftp = ftpUtil.connectFTP();							
							InputStream in = ftp.getFileStream(ftpModel.getFilePath().substring(1, ftpModel.getFilePath().length())+ftpModel.getFileNewName());
							PreviewUtil.fileDirectShow(originalFileName, in, response);
						} catch (Exception e) {
							logger.error(e.getMessage());
							res.setCode(Result.CODE_ERROR);
							res.setMsg("预览文件出错！");
							return res;
						}
					}else{
						res.setCode(Result.CODE_ERROR);
						res.setMsg("非可预览的文件类型！");
						return res;
					}
				}
			}
		}
		return res;	
	}


	/**
	 *	office文件转换为PDF
	 * @param request
	 * @param originalFileName
	 * @param fromFileInputStream
	 * @param currentId
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public String convertToPDF(HttpServletRequest request,String originalFileName,InputStream fromFileInputStream,String currentId){

		String convertFileSavePath = request.getRealPath("/")+"resource/filePreview"+File.separatorChar+currentId;
		File file = new File(convertFileSavePath);
		if(!file.exists()){
			file.mkdirs();
		}
		String type = originalFileName.substring(originalFileName.lastIndexOf(".")+1).toLowerCase();
		try {
			if(type.endsWith("x")){
				return Doc2HtmlUtil.file2pdf(fromFileInputStream, convertFileSavePath, type.substring(0, type.length()-1));
			}else{
				return Doc2HtmlUtil.file2pdf(fromFileInputStream, convertFileSavePath, type);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			return null;
		}

	}
}
